<template>
  <ContentWrap>
    <!-- 搜索工作栏 -->
    <el-form
      class="-mb-15px"
      :model="queryParams"
      ref="queryFormRef"
      :inline="true"
      label-width="68px"
    >
      <el-form-item label="合约名称" prop="name">
        <el-input
          v-model="queryParams.name"
          placeholder="请输入合约名称"
          clearable
          @keyup.enter="handleQuery"
          class="!w-240px"
        />
      </el-form-item>
      <el-form-item label="统计周期" prop="reportDate">
        <el-date-picker
          v-model="queryParams.reportDate"
          value-format="YYYY-MM-DD HH:mm:ss"
          type="daterange"
          start-placeholder="开始日期"
          end-placeholder="结束日期"
          :default-time="[new Date('1 00:00:00'), new Date('1 23:59:59')]"
          class="!w-220px"
        />
        　
        <div class="mr-10px">
          <el-button
            size="small"
            @click="setQuickDateRange('week')"
            class="mr-5px"
          >
            最近一周
          </el-button>
          <el-button
            size="small"
            @click="setQuickDateRange('month')"
            class="mr-5px"
          >
            最近一月
          </el-button>
          <el-button
            size="small"
            @click="setQuickDateRange('threeMonths')"
            class="mr-10px"
          >
            最近三月
          </el-button>
        </div>
      </el-form-item>
      <el-form-item>
        <el-button @click="handleQuery">
          <Icon icon="ep:search" class="mr-5px"/>
          搜索
        </el-button>
        <el-button @click="resetQuery">
          <Icon icon="ep:refresh" class="mr-5px"/>
          重置
        </el-button>
        <el-button
          type="primary"
          plain
          @click="openForm('create')"
          v-hasPermi="['erp:contract-depo:create']"
        >
          <Icon icon="ep:plus" class="mr-5px"/>
          新增
        </el-button>
        <el-button
          type="success"
          plain
          @click="handleExport"
          :loading="exportLoading"
          v-hasPermi="['erp:contract-depo:export']"
        >
          <Icon icon="ep:download" class="mr-5px"/>
          导出
        </el-button>
      </el-form-item>
    </el-form>
  </ContentWrap>

  <!-- 列表 -->
  <ContentWrap>
    <el-table v-loading="loading" :data="list" :stripe="true" :show-overflow-tooltip="true"
              show-summary :summary-method="getSummaries">
      <el-table-column label="合约名称" align="center" prop="name"/>
      <el-table-column
        label="最近持有日期"
        align="center"
        prop="lastHoldDate"
        :formatter="dateFormatter2"
        width="180px"
      />
      <el-table-column label="最近每手保证金" align="right" prop="pricePerLot">
        <template #default="scope">
          {{ (scope.row.pricePerLot) === 0 ? '-' : '￥' + (scope.row.pricePerLot).toFixed(2) }}
        </template>
      </el-table-column>
      <el-table-column label="手数" align="right" prop="lots">
        <template #default="scope">
          <span
            :style="{ color: scope.row.lots > 0 ? 'red' : scope.row.lots < 0? 'green' :'black' }">
            {{ (scope.row.lots) === 0 ? '-' : (scope.row.lots) }}
          </span>
        </template>
      </el-table-column>
      <el-table-column label="基础配额" align="right" prop="basicTotalAmount" width="150px">
        <template #default="scope">
          {{
            (scope.row.basicTotalAmount) === 0 ? '-' : '￥' + (scope.row.basicTotalAmount).toFixed(2)
          }}
        </template>
      </el-table-column>
      <el-table-column label="周期内盈亏" align="right" prop="cycleAmount">
        <template #default="scope">
          <span
            :style="{ color: scope.row.cycleAmount > 0 ? 'red' : scope.row.cycleAmount < 0? 'green' :'black' }">
            {{ (scope.row.cycleAmount) === 0 ? '-' : '￥' + (scope.row.cycleAmount).toFixed(2) }}
          </span>
        </template>
      </el-table-column>
      <el-table-column label="参考配额" align="right" prop="suggestTotalAmount" width="150px">
        <template #default="scope">
          <span
            :style="{ color: scope.row.suggestTotalAmount > 0 ? 'red' : scope.row.suggestTotalAmount < 0? 'green' :'black' }">
            {{ (scope.row.suggestTotalAmount) === 0 ? '-' : '￥' + (scope.row.suggestTotalAmount) }}
          </span>
        </template>
      </el-table-column>
      <el-table-column label="备注" align="left" prop="remark"/>
      <el-table-column label="操作" align="center" min-width="120px">
        <template #default="scope">
          <el-button
            link
            type="primary"
            @click="openForm('update', scope.row.id)"
            v-hasPermi="['erp:contract-depo:update']"
          >
            编辑
          </el-button>
        </template>
      </el-table-column>
    </el-table>
  </ContentWrap>

  <!-- 表单弹窗：添加/修改 -->
  <ContractDepoForm ref="formRef" @success="getList"/>
</template>

<script setup lang="ts">
import download from '@/utils/download'
import {ContractDepoApi, ContractDepoVO} from '@/api/erp/contractdepo'
import ContractDepoForm from './ContractDepoForm.vue'
import {dateFormatter2} from "@/utils/formatTime";

/** 合约基本信息 列表 */
defineOptions({name: 'ContractDepo'})

const message = useMessage() // 消息弹窗
const {t} = useI18n() // 国际化

const loading = ref(true) // 列表的加载中
const list = ref<ContractDepoVO[]>([]) // 列表的数据
const total = ref(0) // 列表的总页数
const queryParams = reactive({
  pageNo: 1,
  pageSize: 1000,
  name: undefined,
  reportDate: []
})
const queryFormRef = ref() // 搜索的表单
const exportLoading = ref(false) // 导出的加载中

/** 查询列表 */
const getList = async () => {
  loading.value = true
  try {
    const data = await ContractDepoApi.getContractDepoPage(queryParams)
    list.value = data.list
    total.value = data.total
  } finally {
    loading.value = false
  }
}

/** 搜索按钮操作 */
const handleQuery = () => {
  queryParams.pageNo = 1
  getList()
}

/** 重置按钮操作 */
const resetQuery = () => {
  queryFormRef.value.resetFields()
  handleQuery()
}

/** 添加/修改操作 */
const formRef = ref()
const openForm = (type: string, id?: number) => {
  formRef.value.open(type, id)
}

/** 删除按钮操作 */
const handleDelete = async (id: number) => {
  try {
    // 删除的二次确认
    await message.delConfirm()
    // 发起删除
    await ContractDepoApi.deleteContractDepo(id)
    message.success(t('common.delSuccess'))
    // 刷新列表
    await getList()
  } catch {
  }
}

/** 导出按钮操作 */
const handleExport = async () => {
  try {
    // 导出的二次确认
    await message.exportConfirm()
    // 发起导出
    exportLoading.value = true
    const data = await ContractDepoApi.exportContractDepo(queryParams)
    download.excel(data, '合约基本信息.xls')
  } catch {
  } finally {
    exportLoading.value = false
  }
}

/** 初始化 **/
onMounted(() => {
  getList()
})

// 新增快速设置日期范围的方法
const setQuickDateRange = (type: 'week' | 'month' | 'threeMonths') => {
  const now = new Date()
  const startDate = new Date(now)

  switch (type) {
    case 'week':
      startDate.setDate(now.getDate() - 7)
      break
    case 'month':
      startDate.setMonth(now.getMonth() - 1)
      break
    case 'threeMonths':
      startDate.setMonth(now.getMonth() - 3)
      break
  }

  // 设置开始时间为当天的 00:00:00
  startDate.setHours(0, 0, 0, 0)

  // 设置结束时间为当前时间的 23:59:59
  const endDate = new Date(now)
  endDate.setHours(23, 59, 59, 999)

  // 更新 queryParams 的日期范围
  queryParams.reportDate = [
    startDate.toISOString().slice(0, 19).replace('T', ' '),
    endDate.toISOString().slice(0, 19).replace('T', ' ')
  ]
}

// 计算总和的方法
const getSummaries = (param: { columns: any[], data: ContractDepoVO[] }) => {
  const { columns, data } = param
  const sums: string[] = []

  columns.forEach((column, index) => {
    if (column.property === 'basicTotalAmount') {
      const total = data.reduce((sum, row) => sum + (row.basicTotalAmount || 0), 0)
      sums[index] = total === 0 ? '-' : `总计：￥${total.toFixed(2)}`
    } else {
      sums[index] = ''
    }
  })

  return sums
}
</script>